package com.imist.servlet;


import com.imist.domain.User;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;


public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //接收数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        List<User> userList = (List<User>) this.getServletContext().getAttribute("list");
        for (User user : userList) {
            //判断用户名时候正确
            if (username .equals(user.getUsername())){
                if (password.equals(user.getPassword())){
                    //登录成功
                    String remember = req.getParameter("remember");
                    if (remember.equals("true")){
                        // 完成记住用户名的功能,默认cookie关闭浏览器就没有了，需要设置一下有效期
                        Cookie cookie = new Cookie("username",user.getUsername());
                        //设置有效路径和有效时间
                        cookie.setPath("/mvc_demo");
                        cookie.setMaxAge(60*60*24);
                        //将cookie写回到浏览器
                        resp.addCookie(cookie);
                    }
                    //将用户信息保存到session中
                    req.getSession().setAttribute("user",user);
                    resp.sendRedirect("/success.jsp");
                    return;
                }
            }
        }
        req.setAttribute("msg","用户密码错误！");
        req.getRequestDispatcher("/login.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
